import pandas as pd
import requests
import datetime
from io import StringIO


def getDate(day=-1):
    now = datetime.datetime.now()
    sta_date_time = (now + datetime.timedelta(days=day)).strftime("%Y-%m-%d 00:00:00")
    end_date_time = (now + datetime.timedelta(days=day + 1)).strftime("%Y-%m-%d 00:00:00")
    date_good = "{0} - {1}".format(sta_date_time, end_date_time)
    return date_good


def getTodaySela(invite):
    url = "http://admin.linjiayoho.com/association/order/order_list.html"
    invite = "&is_self_support=1" if invite == 6 else invite
    payload = 'city=&is_cash=&is_cross_border=&is_gift_repeat=' \
              '&is_invite=%s&is_sale=' \
              '&key=&province=&query_type=1&role=&submit1=1' \
              '&supplyid=&supplyid=' \
              '&timeStr=%s' \
              '&time_change=1&time_type=1' % (invite, getDate())
    print(payload)

    headers = {
        'Upgrade-Insecure-Requests': '1',
        'Origin': 'http://admin.linjiayoho.com',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.112 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Cookie': 'PHPSESSID=64eaatec4e0uclpb6sg3opt300; association_aid=114; association_signin_token=060fe1b6ee9e3b960e14c09fc7436141599d333d; SERVERID=325280ab47a7314f096d8f58ac7bf9e2|1604936476|1604936154'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    response_csv = response.text
    if "当前检索条件没有订单记录" in response_csv:
        return [0, 0]
    dataForm = pd.read_csv(StringIO(response_csv), header=1, usecols=['订单总额', '订单状态', '商品名称'])
    mask = (dataForm["订单状态"] == "待发货") | (dataForm["订单状态"] == "待收货") | (dataForm["订单状态"] == "发货中") | (
            dataForm["订单状态"] == "已完成")
    result = dataForm.loc[mask]
    res = [result.订单总额.sum(), result.shape[0]]
    return res


inv = {"创业礼包": 1, '福利专区': 2, '自营专区': 6, '团品': 5}
make_count = 1
sum_some, sum_order = 0, 0
print("-----开始计算%s销售数据------" % getDate())
for key in inv:
    ok = getTodaySela(inv[key])
    print("%s:%.1f" % (key, ok[0]))
    print('有效订单:%d' % (ok[1]))
    print('------------')
    if make_count < 4:
        sum_some += ok[0]
        sum_order += ok[1]
    if make_count == 3:
        print("礼包&福利&自营合计：%.1f" % sum_some)
        print('有效订单合计:', sum_order)
        print('----------------')
    make_count += 1
